package com.bank.ui.admin;

import com.bank.dao.CustomerDAO;
import com.bank.entity.Customer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class QueryCustomerDialog extends JDialog {
    private final JTextField queryField;
    private final JComboBox<String> queryTypeComboBox;
    private final JTable resultTable;
    private boolean hasSearchResults = false;

    public QueryCustomerDialog() {
        setTitle("查询客户");
        setSize(600, 400);
        setModal(true);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));
        setResizable(false);

        // 查询面板
        JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        queryPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        queryTypeComboBox = new JComboBox<>(new String[]{"精确查询（身份证号）", "模糊查询（姓名）", "范围查询（客户编号）"});
        queryTypeComboBox.setPreferredSize(new Dimension(180, 30));
        queryPanel.add(new JLabel("查询类型:"));
        queryPanel.add(queryTypeComboBox);

        queryField = new JTextField(20);
        queryField.setPreferredSize(new Dimension(200, 30));
        queryPanel.add(new JLabel("查询条件:"));
        queryPanel.add(queryField);

        JButton queryButton = new JButton("查询");
        queryButton.setPreferredSize(new Dimension(80, 30));
        queryButton.addActionListener(this::performQuery);
        queryPanel.add(queryButton);

        add(queryPanel, BorderLayout.NORTH);

        // 结果表格
        resultTable = new JTable();
        resultTable.setFont(new Font("宋体", Font.PLAIN, 14));
        resultTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14));
        resultTable.setRowHeight(25);

        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("查询结果"));
        add(scrollPane, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dispose());
        buttonPanel.add(closeButton);

        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void performQuery(ActionEvent e) {
        String queryText = queryField.getText().trim();
        String queryType = (String) queryTypeComboBox.getSelectedItem();

        if (queryText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入查询条件！", "输入错误", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            CustomerDAO customerDAO = new CustomerDAO();
            List<Customer> customers = new ArrayList<>();

            if ("精确查询（身份证号）".equals(queryType)) {
                // 精确查询
                Customer customer = customerDAO.getCustomerByPID(queryText);
                if (customer != null) {
                    customers.add(customer);
                }
            } else if ("模糊查询（姓名）".equals(queryType)) {
                // 模糊查询
                customers = customerDAO.getCustomersByNameLike(queryText);
            } else if ("范围查询（客户编号）".equals(queryType)) {
                // 范围查询
                if (!queryText.matches("\\d+-\\d+")) {
                    JOptionPane.showMessageDialog(
                            this,
                            "范围格式不正确！请使用'起始编号-结束编号'格式（例如：1001-2000）",
                            "输入错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                    return;
                }

                String[] range = queryText.split("-");
                int startID = Integer.parseInt(range[0]);
                int endID = Integer.parseInt(range[1]);

                if (startID > endID) {
                    JOptionPane.showMessageDialog(
                            this,
                            "起始编号不能大于结束编号！",
                            "输入错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                    return;
                }

                customers = customerDAO.getCustomersByIDRange(startID, endID);
            }

            // 更新表格模型
            updateResultTable(customers);

        } catch (SQLException | NumberFormatException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(
                    this,
                    "查询失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE
            );
        }
    }

    private void updateResultTable(List<Customer> customers) {
        // 创建表头
        String[] columnNames = {"客户编号", "客户姓名", "身份证号", "联系电话", "联系地址"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };

        // 添加数据
        if (customers != null && !customers.isEmpty()) {
            for (Customer customer : customers) {
                model.addRow(new Object[]{
                        customer.getCustomerID(),
                        customer.getCustomerName(),
                        customer.getPID(),
                        customer.getTelephone(),
                        customer.getAddress()
                });
            }
            hasSearchResults = true;
        } else {
            model.addRow(new Object[]{"", "没有找到匹配的记录", "", "", ""});
            hasSearchResults = false;
        }

        resultTable.setModel(model);
    }

    /**
     * 检查是否有查询结果
     */
    public boolean hasSearchResults() {
        return hasSearchResults;
    }
}